package com.jnu.student.myfirstapplication.ui.award;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.student.myfirstapplication.R;
import com.jnu.student.myfirstapplication.data.TaskItem;
import com.jnu.student.myfirstapplication.ui.DataSave;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AwardFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AwardFragment extends Fragment {

    private ArrayList<TaskItem> mAwardsList = new ArrayList<>();
    private ArrayList<TaskItem> mFinishedAwardsList = new ArrayList<>();
    ActivityResultLauncher<Intent> addAwardLauncher;
    ActivityResultLauncher<Intent> refactorAwardLauncher;
    private AwardAdapter adapter_local;
    boolean finished = false;
    public AwardFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment AwardFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AwardFragment newInstance() {
        AwardFragment fragment = new AwardFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_award, container, false);
        TextView nullTipTextView = root.findViewById(R.id.nullTipText);
        FloatingActionButton floatingActionButton = root.findViewById(R.id.addButton);
        floatingActionButton.setVisibility(View.GONE);
        mAwardsList = new DataSave("AwardsList.data").LoadItems(requireActivity());
        mFinishedAwardsList = new DataSave("FinishedAwardsList.data").LoadItems(requireActivity());
        setHasOptionsMenu(true);        // 添加actionbar的一个按钮是作为菜单添加上去的，所以要先可以有菜单，再重载创建菜单函数
        // 添加的数据处理
//        mAwardsList.add(new TaskItem("award1", 20));
//        mAwardsList.add(new TaskItem("award2", 25));
//        mAwardsList.add(new TaskItem("award3", 30));
        RecyclerView recyclerView = root.findViewById(R.id.recycle_award);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireActivity());  //线性的布局管理器
        recyclerView.setLayoutManager(layoutManager);           //为recycleView绑定布局管理器

        AwardAdapter adapter = new AwardAdapter(mAwardsList, false);      //数据管理的适配器
        AwardAdapter awardAdapterFinished = new AwardAdapter(mFinishedAwardsList, true);
        registerForContextMenu(recyclerView);                   //注册上下文菜单
        recyclerView.setAdapter(adapter);                       //绑定适配器
        adapter_local = adapter;
        if (adapter_local.mlist.isEmpty() == true) {
            nullTipTextView.setText("数据为空，请添加数据");
            nullTipTextView.setVisibility(View.VISIBLE);
        } else {
            nullTipTextView.setVisibility(View.GONE);
        }

        Switch changeFinished = root.findViewById(R.id.finishedAwards);
        changeFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!b)
                {
                    compoundButton.setText("当前在奖励列表中");
                    recyclerView.setAdapter(adapter);                       //绑定适配器
                    adapter_local = adapter;
                    finished = true;
                    if (adapter_local.mlist.isEmpty() == true) {
                        nullTipTextView.setText("奖励列表为空，请添加数据");
                        nullTipTextView.setVisibility(View.VISIBLE);
                    } else {
                        nullTipTextView.setVisibility(View.GONE);
                    }
                } else{
                    compoundButton.setText("当前在已完成奖励的列表中");
                    recyclerView.setAdapter(awardAdapterFinished);                       //绑定适配器
                    adapter_local = awardAdapterFinished;
                    finished = false;
                    if (adapter_local.mlist.isEmpty() == true) {
                        nullTipTextView.setText("没有已完成的奖励，请在奖励列表界面完成奖励");
                        nullTipTextView.setVisibility(View.VISIBLE);
                    } else {
                        nullTipTextView.setVisibility(View.GONE);
                    }
                }
            }
        });

        addAwardLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        String name = data.getStringExtra("name"); // 获取返回的数据
                        int score = data.getIntExtra("score", -1);

                        mAwardsList.add(new TaskItem(name, score));   // 添加数据
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave("AwardsList.data").SaveItems(requireActivity(), mAwardsList);
                        adapter.notifyItemInserted(mAwardsList.size());  // 适配器重新适配一下新出现的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        refactorAwardLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        int position = data.getIntExtra("position",0);
                        String name = data.getStringExtra("name"); // 获取返回的数据
                        int score = data.getIntExtra("score", -1); // 获取返回的数据

                        mAwardsList.get(position).Rename(name);   // 修改数据
                        mAwardsList.get(position).Rescore(score);

//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave("AwardsList.data").SaveItems(requireActivity(), mAwardsList);
                        adapter.notifyItemChanged(position);  // 适配器重新适配一下新改变的item

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        return root;
    }
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.award_menu, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add_award_menu) {
            // 切换到添加奖励的activity并传递数据
            Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
            Intent intentAdd = new Intent(requireActivity(), AddAwardActivity.class);   // 从当前activity里创建有关参数二那个类的activity
            addAwardLauncher.launch(intentAdd);     // 执行新activity并处理返回结果
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 点击菜单后的响应事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // 处理菜单项的点击事件
        switch (item.getItemId()) {
            case 0:
                // 菜单项1的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("删除奖励"+ item.getOrder());
                builder.setMessage("确定删除这一奖励吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAwardsList.remove(item.getOrder());
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                        new DataSave("AwardsList.data").SaveItems(requireActivity(), mAwardsList);
                        adapter_local.notifyItemRemoved(item.getOrder());
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
                break;
            case 1:
                // 菜单项2的点击事件处理逻辑
                Toast.makeText(requireActivity(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                Intent intentRename = new Intent(requireActivity(), AddAwardActivity.class);
                TaskItem ItemRefactor= mAwardsList.get(item.getOrder());
                intentRename.putExtra("name",ItemRefactor.getTaskName());
                intentRename.putExtra("score",ItemRefactor.getTaskScore());
                intentRename.putExtra("position",item.getOrder());
                refactorAwardLauncher.launch(intentRename);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }
    public class AwardAdapter extends RecyclerView.Adapter<AwardFragment.AwardAdapter.ViewHolder> {
        private ArrayList<TaskItem> mlist;
        private final boolean IsFinished;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
            private final TextView title;
            private final TextView score;

            public ViewHolder(View view) {
                super(view);
                title = (TextView) view.findViewById(R.id.award_title);
                score = (TextView) view.findViewById(R.id.award_score);
                view.setLongClickable(true);                    // 长按响应
                view.setOnCreateContextMenuListener(this);      // 创建上下文菜单
                view.setLongClickable(true);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (IsFinished == false) {
                            Toast.makeText(requireActivity(), "奖励消耗点数中", Toast.LENGTH_SHORT).show();
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                            int score = Integer.parseInt(((TextView) v.findViewById(R.id.award_score)).getText().toString().substring(1));
                            builder.setTitle("奖励需要消耗点数" + score);
                            builder.setMessage("确定消耗点数吗？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int position = getAdapterPosition();
                                    mFinishedAwardsList.add(mAwardsList.get(position));
                                    mAwardsList.remove(position);
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                                    new DataSave("AwardsList.data").SaveItems(requireActivity(), mAwardsList);
                                    new DataSave("FinishedAwardsList.data").SaveItems(requireActivity(), mFinishedAwardsList);
                                    adapter_local.notifyItemRemoved(position);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        }
                        else {
                            Toast.makeText(requireActivity(), "撤销已完成的奖励中", Toast.LENGTH_SHORT).show();
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                            int score = Integer.parseInt(((TextView) v.findViewById(R.id.award_score)).getText().toString().substring(1));
                            builder.setTitle("撤销已完成的奖励，将会归还点数" + score);
                            builder.setMessage("确定撤销完成吗？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int position = getAdapterPosition();
                                    mAwardsList.add(mFinishedAwardsList.get(position));
                                    mFinishedAwardsList.remove(position);
//                        new DataBank().SaveBookItems(requireActivity(), mAwardsList);
                                    new DataSave("AwardsList.data").SaveItems(requireActivity(), mAwardsList);
                                    new DataSave("FinishedAwardsList.data").SaveItems(requireActivity(), mFinishedAwardsList);
                                    adapter_local.notifyItemRemoved(position);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        }
                    }
                });
            }
            public TextView getTitle() {
                return title;
            }

            public TextView getScore() {
                return score;
            }

            // 上下文菜单的样子设定
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                if (IsFinished == false) {
                    menu.setHeaderTitle("具体操作");
                    menu.add(0, 0, this.getAdapterPosition(), "删除");
                    menu.add(0, 1, this.getAdapterPosition(), "修改");
                }
            }
        }

        public AwardAdapter(ArrayList<TaskItem> mlist, boolean IsFinished) {
            this.mlist = mlist;
            this.IsFinished = IsFinished;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.award_detail, parent, false);
            return new AwardFragment.AwardAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull AwardFragment.AwardAdapter.ViewHolder holder, int position) {
            TaskItem awardItem = mlist.get(position);
            holder.getTitle().setText(awardItem.getTaskName());
            holder.getScore().setText("-"+awardItem.getTaskScore());
        }

        @Override
        public int getItemCount() {
            return mlist.size();
        }
        // 实现必要的方法
    }
}